package com.zareal.ymcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.zareal.ymcc.domain.PayOrder;
import com.zareal.ymcc.dto.PayDto;
import com.zareal.ymcc.enums.GlobalErrorCode;
import com.zareal.ymcc.service.IPayOrderService;
import com.zareal.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "tx-course-order-consumer-group",
        topic = "tx-course-order-topic",
        selectorExpression = "tx-course-order-tag"
)
public class CourseOrderPayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取字符集
        byte[] body = messageExt.getBody();
        String paramStr = new String(body, StandardCharsets.UTF_8);
        PayDto payDto = JSON.parseObject(paramStr, PayDto.class);
        AssertUtil.isNotNull(payDto, GlobalErrorCode.ORDER_TO_PAY_IS_NULL);
        PayOrder payOrder = payOrderService.selectByOrderNo(payDto.getOrderNo());

        // 2.1判断订单是否存在
            // 如果存在直接返回，说明已经保存，不是用户的问题不用直接抛错
        if (payOrder != null) {
            log.info("课程订单：{}，已生成支付单，签收成功！", payDto.getOrderNo());
            return;
        }
        // 2.保存支付单
        payOrder = new PayOrder();
        payOrder.setAmount(payDto.getTotalAmount());
        payOrder.setCreateTime(new Date());
        payOrder.setOrderNo(payDto.getOrderNo());
        payOrder.setPayStatus(PayOrder.WAIT_PAY_STATUS);
        payOrder.setPayType(payDto.getPayType());
        payOrder.setUserId(payDto.getUserId());
        payOrder.setSubject(payDto.getTitle());
        payOrderService.insert(payOrder);
    }
}
